package pl.edu.agh.xls2html.htmlelements;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.util.CellRangeAddress;

public class CellProperties {
	// Wspolczynniki skalujace
	public static int SCALE_WIDTH = 32; // wynika z dziwnego formatu jednostek
	// uzywanych w xls
	public static int SCALE_HEIGHT = 16; // wynika z dziwnego formatu jednostek
	// uzywanych w xls

	private int colspan = 0;
	private int rowspan = 0;
	private Boolean firstInRange;
	private Boolean inRange;
	private CellRangeAddress range;
	private HSSFCell cell = null;

	public CellProperties(HSSFCell cell) {
		this.cell = cell;
		inRange = false;
		firstInRange = false;
		colspan = 0;
		rowspan = 0;
		CellRangeAddress region = null;
		int num = cell.getSheet().getNumMergedRegions();
		for (int i = 0; i < num; i++) {
			region = cell.getSheet().getMergedRegion(i);
			if (isInRegion(region)) {
				inRange = true;
				rowspan = region.getLastRow() - region.getFirstRow() + 1;
				colspan = region.getLastColumn() - region.getFirstColumn() + 1;
				if (region.getFirstColumn() == cell.getColumnIndex()
						&& region.getFirstRow() == cell.getRowIndex())
					firstInRange = true;
				break;
			}
		}
		range = region;
	}

	public int getColspan() {
		return colspan;
	}

	public int getRowspan() {
		return rowspan;
	}

	public Boolean isFirstInRange() {
		return firstInRange;
	}

	public Boolean isInRange() {
		return inRange;
	}

	public CellRangeAddress getRange() {
		return range;
	}

	public int getRangeWidth() {
		int res = 0;
		for (int i = range.getFirstColumn(); i <= range.getLastColumn(); i++) {
			int w = cell.getSheet().getColumnWidth(i) / SCALE_WIDTH;
			res += w;
		}
		return res;
	}

	public int getRangeHeigt() {
		int res = 0;
		for (int i = range.getFirstRow(); i <= range.getLastRow(); i++) {
			int h = cell.getSheet().getColumnWidth(i) / SCALE_WIDTH;
			HSSFRow r = cell.getSheet().getRow(i);
			if (r != null)
				h = r.getHeight() / SCALE_HEIGHT + 2;
			res += h;
		}
		return res;
	}

	private Boolean isInRegion(CellRangeAddress region) {
		return cell.getRowIndex() >= region.getFirstRow()
				&& cell.getRowIndex() <= region.getLastRow()
				&& cell.getColumnIndex() >= region.getFirstColumn()
				&& cell.getColumnIndex() <= region.getLastColumn();
	}

}
